package com.qbw.app.module.home.holder;

import android.content.Context;
import android.location.Location;
import android.view.View;
import android.view.ViewGroup;

import androidx.recyclerview.widget.GridLayoutManager;

import com.http.okhttp.HttpTask;
import com.lib.util.ResUtil;
import com.lib.util.ScreenUtil;
import com.qbw.app.Constant;
import com.qbw.app.R;
import com.qbw.app.databinding.HomeHolderInfoBinding;
import com.qbw.app.manager.LocationManager;
import com.qbw.app.manager.UnitManager;
import com.qbw.app.model.Coolant;
import com.qbw.app.model.ProblemStatus;
import com.qbw.app.model.Vehicle;
import com.qbw.app.model.VehicleHomeInfo;
import com.qbw.app.model.Voltage;
import com.qbw.app.model.Warning;
import com.qbw.app.model.Weather;
import com.qbw.app.module.common.holder.CommonHolder;
import com.qbw.app.module.home.adapter.HomeAdapter;
import com.qbw.app.module.home.adapter.HomeViewType;
import com.qbw.app.module.vehicle.VehicleDataBindingAdapter;
import com.qbw.app.module.vehicle.activity.VehicleEstimateDistanceActivity;
import com.qbw.app.module.vehicle.activity.VehicleWarningActivity;
import com.qbw.app.module.vehicle.popwindow.VehicleSelectPopWindow;
import com.qbw.app.request.impl.CommonRequest;
import com.qbw.core.model.ViewType;
import com.qbw.l.L;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import static com.qbw.app.request.impl.VehicleRequest.METHOD_COOLANT;
import static com.qbw.app.request.impl.VehicleRequest.METHOD_HOME_INFO;
import static com.qbw.app.request.impl.VehicleRequest.METHOD_HOME_STATUS;
import static com.qbw.app.request.impl.VehicleRequest.METHOD_VOLTAGE;

/**
 * @author QBW
 * @date 2019/8/17
 */
@Deprecated
public class HomeInfoHolder extends CommonHolder<Vehicle.VehicleList, HomeHolderInfoBinding> implements HttpTask.CallBack {

    private HttpTask mVoltageTask;
    private HttpTask mCoolantTask;
    private HttpTask mStatusTask;
    private HttpTask mInfoTask;
    private HomeAdapter mStatusAdapter;
    private List<Integer> mStatusChildSortedViewTypes = new ArrayList<>();

    public HomeInfoHolder(Context context, ViewGroup viewParent) {
        super(context, R.layout.home_holder_info, viewParent);
        GridLayoutManager gmStatus = new GridLayoutManager(context, 3);
        mBinding.rcvStatus.setLayoutManager(gmStatus);
        mBinding.rcvStatus.setItemAnimator(null);
        mStatusAdapter = new HomeAdapter(context, mListener);
        mBinding.rcvStatus.setAdapter(mStatusAdapter);
        mStatusChildSortedViewTypes.add(HomeViewType.VT_STATUS_ITEM_BATTERY);
        mStatusChildSortedViewTypes.add(HomeViewType.VT_STATUS_ITEM_COOLANT);
        mStatusChildSortedViewTypes.add(HomeViewType.VT_STATUS_ITEM_PROBLEM);
    }

    @Override
    public void bindData(int position, Vehicle.VehicleList data) {
        super.bindData(position, data);
        //mStatusAdapter.clear();
        /*List<HomeStatusItemHolder.Data> statusDatas = new ArrayList<>();
        statusDatas.add(new HomeStatusItemHolder.Data(R.string.voltage, 0));
        statusDatas.add(new HomeStatusItemHolder.Data(R.string.coolant, 0));
        statusDatas.add(new HomeStatusItemHolder.Data(R.string.problem, 0));
        mStatusAdapter.addChild(statusDatas);*/
        mBinding.rcvStatus.setVisibility(View.VISIBLE);
        /*mStatusAdapter.addChild(new Voltage());
        mStatusAdapter.addChild(new Coolant());
        mStatusAdapter.addChild(new ProblemStatus());*/
        mBinding.tvUnitLicheng.setText(UnitManager.getInstance().isUseKm() ? "km" : "mile");
        mBinding.tvYuguLichengLabel.setOnClickListener(mOnClickListenerYuguLicheng);
        mBinding.tvYuguLichengValue.setOnClickListener(mOnClickListenerYuguLicheng);
        Vehicle selectedVehicle = data.getIndexVehicle();
        if (selectedVehicle != null) {
            mBinding.tvVehicleName.setText(selectedVehicle.getVehicleNick() + (selectedVehicle.getDrivingState() == Constant.VEHICLE_STATUS_OFFLINE ? (String
                    .format(Locale.getDefault(),
                            "(%s)",
                            mContext.getResources().getString(R.string.offline))) : ""));
        }
        //mBinding.tvWarningMessage.setOnClickListener(mClickListenerProblem);
        mBinding.llCurrentVehicle.setOnClickListener(mClickListenerSelectVehicle);
        mBinding.ivWarningMessage.setOnClickListener(mClickListenerWarning);
        mBinding.tvWarningMessage.setOnClickListener(mClickListenerWarning);
        //是否显示剩余油量，如果剩余油量不显示，那么预估里程默认也不显示
        boolean showOilRemainder = selectedVehicle != null && selectedVehicle.hasMenuId(Vehicle.MENU_ID_OIL_REMAINDER);
        mBinding.tvBatteryValue.setVisibility(showOilRemainder ? View.VISIBLE : View.GONE);
        mBinding.tvBatteryLabel.setVisibility(mBinding.tvBatteryValue.getVisibility());
        mBinding.tvUnitBattery.setVisibility(mBinding.tvBatteryValue.getVisibility());
        //是否显示预估里程
        boolean showLicheng = selectedVehicle != null && selectedVehicle.hasMenuId(Vehicle.MENU_ID_ESTIMATEDMILEAGE);
        if (!showOilRemainder) {
            showLicheng = false;
        }
        mBinding.tvYuguLichengValue.setVisibility(showLicheng ? View.VISIBLE : View.GONE);
        mBinding.tvYuguLichengLabel.setVisibility(mBinding.tvYuguLichengValue.getVisibility());
        mBinding.tvUnitLicheng.setVisibility(mBinding.tvYuguLichengValue.getVisibility());
        if (showLicheng) {
            mBinding.tvBatteryValue.setOnClickListener(mOnClickListenerYuguLicheng);
            mBinding.tvBatteryLabel.setOnClickListener(mOnClickListenerYuguLicheng);
        } else {
            mBinding.tvBatteryValue.setOnClickListener(null);
            mBinding.tvBatteryLabel.setOnClickListener(null);
        }
        //是否显示电瓶电压
        boolean showVoltage = selectedVehicle != null && selectedVehicle.hasMenuId(Vehicle.MENU_ID_BATTERYVOLTAGE);
        if (showVoltage) {
            getVoltage();
        } else {
            //mStatusAdapter.removeChildByObjectType(Voltage.class);
            mStatusAdapter.removeChildByViewType(HomeViewType.VT_STATUS_ITEM_BATTERY);
            checkNoStatusData();
        }
        //是否显示发动机温度
        boolean showCoolant = selectedVehicle != null && selectedVehicle.hasMenuId(Vehicle.MENU_ID_COOLANTTEMPERATURE);
        if (showCoolant) {
            getCoolant();
        } else {
            //mStatusAdapter.removeChildByObjectType(Coolant.class);
            mStatusAdapter.removeChildByViewType(HomeViewType.VT_STATUS_ITEM_COOLANT);
            checkNoStatusData();
        }
        //getStatus();
        //在info接口里面判断是否显示故障
        getInfo();
        itemView.setOnClickListener(mClickListenerItem);
        //获取天气
        Location location = LocationManager.getInstance().getLastLocation();
        if (location != null) {
            mGeneralManager.getRequestManager()
                           .getCommonRequest()
                           .getWeather(location.getLatitude() + "",
                                       location.getLongitude() + "",
                                       "",
                                       this)
                           .execute();
        }
    }

    private void updateWarningUi(Warning.HomeInfo homeInfo) {
        if (homeInfo == null) {
            return;
        }
        if (homeInfo.getUnRead() <= 0) {
            mBinding.tvWarningMessage.setText(R.string.warning_message);
        } else if (homeInfo.getUnRead() == 1) {
            if (homeInfo.getAlarmInfo() != null) {
                mBinding.tvWarningMessage.setText(String.format(ResUtil.getString(R.string.warning_unread_message_one_format),
                                                                homeInfo.getAlarmInfo()
                                                                        .getAlarmName()));
            }
        } else {
            VehicleDataBindingAdapter.setWarningUnreadMany(mBinding.tvWarningMessage,
                                                           homeInfo.getUnRead());
        }
        mBinding.ivWarningMessage.setImageResource(homeInfo.getUnRead() <= 0 ? R.drawable.home_no_warning : R.drawable.home_have_warning);
    }

    @Override
    protected void onClickItem() {

    }

    private View.OnClickListener mClickListenerSelectVehicle = v -> {
        VehicleSelectPopWindow window = new VehicleSelectPopWindow(mContext, mData);
        window.showAsDropDown(v, ScreenUtil.dp2px(mContext, 13), ScreenUtil.dp2px(mContext, 10));
    };

    private ViewGroup.OnClickListener mOnClickListenerYuguLicheng = v -> {
        Vehicle selectedVehicle = mData.getIndexVehicle();
        if (selectedVehicle != null) {
            VehicleEstimateDistanceActivity.start(mContext, selectedVehicle);
        }
    };

    /*private View.OnClickListener mClickListenerProblem = v -> {
        Vehicle selectedVehicle = mData.getIndexVehicle();
        if (selectedVehicle != null) {
            VehicleProblemActivity.startActivity(mContext, selectedVehicle.getVehicleCode());
        }
    };
*/
    private View.OnClickListener mClickListenerWarning = v -> {
        Vehicle selectedVehicle = mData.getIndexVehicle();
        if (selectedVehicle != null) {
            VehicleWarningActivity.startActivity(mContext, selectedVehicle);
        }
    };

    /**
     * 故障，电压，冷却液
     */
    private void getStatus() {
        //if (mStatusTask == null || isSelectedVehicleChanged(mStatusTask.getParams())) {
        Vehicle selectedVehicle = mData.getIndexVehicle();
        if (selectedVehicle != null) {
            mStatusTask = mGeneralManager.getRequestManager()
                                         .getVehicleRequest()
                                         .getHomeStatus(selectedVehicle.getVehicleCode(), this)
                                         .execute();
        }
        //}
    }

    /**
     * 电压
     */
    private void getVoltage() {
        //if (mVoltageTask == null || isSelectedVehicleChanged(mVoltageTask.getParams())) {
        if (mVoltageTask != null) {
            mVoltageTask.cancel();
        }
        Vehicle selectedVehicle = mData.getIndexVehicle();
        if (selectedVehicle != null) {
            mVoltageTask = mGeneralManager.getRequestManager()
                                          .getVehicleRequest()
                                          .getVoltage(selectedVehicle.getVehicleCode(), this)
                                          .execute();
        }

        //}

    }

    /**
     * 冷却液
     */
    private void getCoolant() {
        //if (mCoolantTask == null || isSelectedVehicleChanged(mCoolantTask.getParams())) {
        if (mCoolantTask != null) {
            mCoolantTask.cancel();
        }
        Vehicle selectedVehicle = mData.getIndexVehicle();
        if (selectedVehicle != null) {
            mCoolantTask = mGeneralManager.getRequestManager()
                                          .getVehicleRequest()
                                          .getCoolant(selectedVehicle.getVehicleCode(), this)
                                          .execute();
        }
        //}
    }

    /**
     * 包括了电瓶电压和预估里程（也包括了另外三个接口的数据，但，另外三个接口在这个接口出来之前已经写了，暂不修改）
     */
    private void getInfo() {
        //if (mInfoTask == null || isSelectedVehicleChanged(mInfoTask.getParams())) {
        if (mInfoTask != null) {
            mInfoTask.cancel();
        }
        Vehicle selectedVehicle = mData.getIndexVehicle();
        if (selectedVehicle != null) {
            mInfoTask = mGeneralManager.getRequestManager()
                                       .getVehicleRequest()
                                       .getHomeInfo(selectedVehicle.getVehicleCode(), this)
                                       .execute();
        } else {
            //mStatusAdapter.removeChildByObjectType(ProblemStatus.class);
            mStatusAdapter.removeChildByViewType(HomeViewType.VT_STATUS_ITEM_PROBLEM);
            checkNoStatusData();
        }
        //}
    }

    private boolean isSelectedVehicleChanged(Map<String, Object> requestParams) {
        Vehicle selectedVehicle = mData.getIndexVehicle();
        if (selectedVehicle != null) {
            String taskVehicle = (String) requestParams.get("vehicleCode");
            if (!selectedVehicle.getVehicleCode().equals(taskVehicle)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void onHttpStart(HttpTask httpTask) {

    }

    @Override
    public void onHttpSuccess(HttpTask httpTask, Object entity) {
        if (httpTask.isCanceled()) {
            L.GL.w("method[%s] canceled", httpTask.getMethod());
            return;
        }
        String method = httpTask.getMethod();
        if (METHOD_VOLTAGE.equals(method)) {
            Voltage.Response response = (Voltage.Response) entity;
            Voltage voltage = response.getData();
            voltage.setVehicle(mData.getIndexVehicle());
            int p = mStatusAdapter.getChildPositionByViewType(HomeViewType.VT_STATUS_ITEM_BATTERY);
            ViewType viewType = new ViewType(HomeViewType.VT_STATUS_ITEM_BATTERY, voltage);
            if (p == -1) {
                mStatusAdapter.addChild(mStatusAdapter.getChildPosition(HomeViewType.VT_STATUS_ITEM_BATTERY,
                                                                        mStatusChildSortedViewTypes),
                                        viewType);
                checkNoStatusData();
            } else {
                mStatusAdapter.updateChild(p, viewType);
            }
        } else if (METHOD_COOLANT.equals(method)) {
            Coolant.Response response = (Coolant.Response) entity;
            response.getData().setVehicleCode(mData.getIndexVehicleCode());
            response.getData().setVehicle(mData.getIndexVehicle());
            /*mStatusAdapter.updateChild(mStatusAdapter.getChildPositionByClass(Coolant.class),
                                       response.getData());
*/
            int p = mStatusAdapter.getChildPositionByViewType(HomeViewType.VT_STATUS_ITEM_COOLANT);
            ViewType viewType = new ViewType(HomeViewType.VT_STATUS_ITEM_COOLANT,
                                             response.getData());
            if (p == -1) {
                mStatusAdapter.addChild(mStatusAdapter.getChildPosition(HomeViewType.VT_STATUS_ITEM_COOLANT,
                                                                        mStatusChildSortedViewTypes),
                                        viewType);
                checkNoStatusData();
            } else {
                mStatusAdapter.updateChild(p, viewType);
            }
        } else if (METHOD_HOME_STATUS.equals(method)) {
           /* HomeStatus.Response response = (HomeStatus.Response) entity;
            HomeStatus homeStatus = response.getData();
            ProblemStatus status = new ProblemStatus();
            status.setState(homeStatus.getState());
            status.setFaultCount(homeStatus.getFaultCount());
            status.setVehicleCode(mData.getIndexVehicleCode());
            mStatusAdapter.updateChild(2, status);*/
        } else if (method.equals(METHOD_HOME_INFO)) {
            VehicleHomeInfo.Response response = (VehicleHomeInfo.Response) entity;
            VehicleHomeInfo homeInfo = response.getData();
            updateWarningUi(homeInfo.getAlarmInfo());
            mBinding.setMileage(homeInfo.getMileage());
            mBinding.setResidualFuel(homeInfo.getResidualFuel());
            mBinding.executePendingBindings();
            updateResidualFuelUi(homeInfo.getResidualFuel());
            updateMileagelUi(homeInfo.getMileage());

            //是否显示故障
            boolean showFault = mData.getIndexVehicle().hasMenuId(Vehicle.MENU_ID_VEHICLEBREAKDOWN);
            if (showFault) {
                ProblemStatus fault = homeInfo.getFault();
                ProblemStatus status = new ProblemStatus();
                status.setState(fault.getState() + "");
                status.setFaultCount(fault.getValue());
                status.setVehicleCode(mData.getIndexVehicleCode());
                status.setVehicle(mData.getIndexVehicle());
                /*mStatusAdapter.updateChild(mStatusAdapter.getChildPositionByClass(ProblemStatus.class),
                                           status);*/
                int p = mStatusAdapter.getChildPositionByViewType(HomeViewType.VT_STATUS_ITEM_PROBLEM);
                ViewType viewType = new ViewType(HomeViewType.VT_STATUS_ITEM_PROBLEM, status);
                if (p == -1) {
                    mStatusAdapter.addChild(mStatusAdapter.getChildPosition(HomeViewType.VT_STATUS_ITEM_PROBLEM,
                                                                            mStatusChildSortedViewTypes),
                                            viewType);
                    checkNoStatusData();
                } else {
                    mStatusAdapter.updateChild(p, viewType);
                }
            } else {
                //mStatusAdapter.removeChildByObjectType(ProblemStatus.class);
                mStatusAdapter.removeChildByViewType(HomeViewType.VT_STATUS_ITEM_PROBLEM);
                checkNoStatusData();
            }
        } else if (method.equals(CommonRequest.METHOD_WEATHER)) {
            Weather.Response res = (Weather.Response) entity;
            Weather weather = res.getData();
            mBinding.tvTianqi.setText(String.valueOf(weather.getMain().getTemp()));
        }
    }

    @Override
    public void onHttpFailed(HttpTask httpTask, int errorCode, String message) {
        String method = httpTask.getMethod();
        if (METHOD_VOLTAGE.equals(method)) {
            //mStatusAdapter.removeChildByObjectType(Voltage.class);
            mStatusAdapter.removeChildByViewType(HomeViewType.VT_STATUS_ITEM_BATTERY);
            checkNoStatusData();
        } else if (METHOD_COOLANT.equals(method)) {
            //mStatusAdapter.removeChildByObjectType(Coolant.class);
            mStatusAdapter.removeChildByViewType(HomeViewType.VT_STATUS_ITEM_COOLANT);
            checkNoStatusData();
        } else if (method.equals(METHOD_HOME_INFO)) {
            //mStatusAdapter.removeChildByObjectType(ProblemStatus.class);
            mStatusAdapter.removeChildByViewType(HomeViewType.VT_STATUS_ITEM_PROBLEM);
            checkNoStatusData();
            updateResidualFuelUi(null);
            updateMileagelUi(null);
        } else if (method.equals(CommonRequest.METHOD_WEATHER)) {

        }
    }

    private void checkNoStatusData() {
        if (mStatusAdapter.getChildCount() <= 0) {
            mBinding.rcvStatus.setVisibility(View.GONE);
        } else {
            mBinding.rcvStatus.setVisibility(View.VISIBLE);
            GridLayoutManager gmStatus = new GridLayoutManager(mContext,
                                                               mStatusAdapter.getChildCount());
            mBinding.rcvStatus.setLayoutManager(gmStatus);
        }
    }

    /**
     * 剩余油量
     */
    private void updateResidualFuelUi(VehicleHomeInfo.ResidualFuel fuel) {
        if (fuel == null || (fuel.getState() + "").equals(Voltage.NO_DATA)) {
            mBinding.tvBatteryValue.setText(R.string.na);
        }
    }

    /**
     * 预估里程
     */
    private void updateMileagelUi(VehicleHomeInfo.Mileage mileage) {
        if (mileage == null || (mileage.getState() + "").equals(Voltage.NO_DATA)) {
            mBinding.tvYuguLichengValue.setText(R.string.na);
        }
    }
}
